/**
 * 用户相关服务
 */
const app = getApp()
const util = require('../utils/util.js');
const request = require('../utils/request.js');
/**
 * 微信登录授权
 */
function login() {
  return new Promise(function (resolve, reject) {
    wx.showModal({
      title: '微信授权',
      content: '请求获取您的昵称、头像等信息',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.login({
            success: (res) => {
              wx.setStorageSync('code', res.code)
            }
          })

          wx.getUserProfile({
            desc: '展示用户信息',
            success: (res) => {
              let cloudID = res.cloudID
              let encryptedData = res.encryptedData
              let iv = res.iv
              let signature = res.signature
              let userInfo = res.userInfo
              let code = wx.getStorageSync('code')
              wx.setStorageSync('userProfile', res)

              let obj = {
                url: "/public/wxApp/auth",
                method: "POST",
                data: {
                  code: code,
                  nickName: userInfo.nickName,
                  avatarUrl: userInfo.avatarUrl
                }
              }
              request.loginRequest(obj).then(res => {

                if (res.data.code == 200) {

                  wx.setStorage({
                    key: "token",
                    data: res.data.data,
                    success: () => {
                      console.log("success");
                      request.wxRequest({
                        url: "/getInfo",
                        method: "GET"
                      }).then(info => {
                        if (info.data.code == 200) {
                          wx.setStorageSync('roles', info.data.roles)
                          wx.setStorageSync('user', info.data.user)
                          resolve(info.data.user)
                        }
                      })
                    },
                    fail: () => {
                      console.log("fail");
                    }
                  })


                  // wx.setStorageSync('token', res.data)

                }

              })

            },
            fail: () => {
              console.log('用户取消授权')
              wx.switchTab({
                url: '/pages/normal/index/index/index',
              })
            }
          })

        } else if (res.cancel) {
          console.log('用户点击取消')
          wx.switchTab({
            url: '/pages/normal/index/index/index',
          })
        }
      }
    })
  })
  /**
   *
         // wx.showModal({
        //   title: '微信授权',
        //   content: '请求获取您的昵称、头像等信息',
        //   success(res) {
        //     if (res.confirm) {
        //       console.log('用户点击确定')
        //       wx.login({
        //         success: (res) => {
        //           console.log("res", res);
        //         }
        //       })

        //       wx.getUserProfile({
        //         desc: '展示用户信息',
        //         success: (res) => {
        //           let cloudID = res.cloudID
        //           let encryptedData = res.encryptedData
        //           let iv = res.iv
        //           let signature = res.signature
        //           let userInfo = res.userInfo
        //           wx.setStorageSync('userInfo', userInfo)
        //           wx.setStorageSync('token', "1111")
        //           that.setData({
        //             userInfo: userInfo
        //           })
        //         },
        //         fail: () => {
        //           console.log('用户取消授权')
        //           wx.switchTab({
        //             url: '/pages/normal/index/index/index',
        //           })
        //         }
        //       })

        //     } else if (res.cancel) {
        //       console.log('用户点击取消')
        //       wx.switchTab({
        //         url: '/pages/normal/index/index/index',
        //       })
        //     }
        //   }
        // })
   */

}
/**
 * 通用获取用户信息
 */
function justGetUserInfo() {
  return new Promise(function (resolve, reject) {
    request.wxRequest({
      url: "/getInfo",
      method: "GET"
    }).then(info => {
      if (info.data.code == 200) {
        wx.setStorageSync('roles', info.data.roles)
        wx.setStorageSync('user', info.data.user)
        wx.setStorageSync('permissions', info.data.permissions)
        if (!!info.data.user.phonenumber) wx.setStorageSync('phone', info.data.user.phonenumber)
        resolve(info.data.user)
      }
    })
  })
}
/**
 * 授权获取手机号
 */
function getPhone() {
  return new Promise(function (resolve, reject) {
    wx.showModal({
      title: '手机号授权',
      content: '请求获取您的手机号',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')



        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  })
}
/**
 * 判断用户是否登录
 */
function checkLogin() {
  return new Promise(function (resolve, reject) {
    if (wx.getStorageSync('user') && wx.getStorageSync('token')) {
      resolve(true);
    } else {
      wx.clearStorageSync()
      reject(false);
    }

  });
}
/**
 * 判断用户是否授权手机号
 */
function checkPhone() {
  return new Promise(function (resolve, reject) {
    let user = wx.getStorageSync('user')
    if (user) {
      if (user.phonenumber) {
        resolve(true)
      }else{
        reject(false);
      }
    }else{
      reject(false);
    }
    // if (wx.getStorageSync('phone')) {
    //   resolve(true);
    // } else {
    //   wx.clearStorageSync()
    //   reject(false);
    // }

  });
}
/**
 * 丢弃
 * Promise封装wx.checkSession
 */
function checkSession() {
  return new Promise(function (resolve, reject) {
    wx.checkSession({
      success: function () {
        console.log("处于登录状态");
        resolve(true);
      },
      fail: function () {
        console.log("需要重新登录");
        reject(false);
      }
    })
  });
}

/**
 * 丢弃
 * Promise封装wx.login
 */
// function login() {
//   return new Promise(function (resolve, reject) {
//     wx.login({
//       success: function (res) {
//         console.log('用户参数', res);
//         if (res.code) {
//           // wx.navigateBack({
//           //   delta: 1
//           // })
//           resolve(res);
//         } else {
//           reject(res);
//         }
//       },
//       fail: function (err) {
//         reject(err);
//       }
//     });
//   });
// }



/**
 * 调用微信登录
 * 丢弃
 */
function loginByWeixin(userInfo) {

  return new Promise(function (resolve, reject) {
    return login().then((res) => {
      var postObj = {
        url: '/mobileUser/authorizedLogin',
        data: {
          code: res.code,
          userInfo: userInfo
        },
        method: 'post'
      }
      request.loginRequest(postObj).then(res => {
        if (res.data.code === 200) {
          //存储用户信息
          console.log('存储用户信息', res);
          wx.setStorageSync('userInfo', res.data.data.userInfo);
          wx.setStorageSync('token', res.data.data.token);
          // app.globalData.hasLogin = true;
          // app.globalData.userInfo = res.data.data.userInfo
          // wx.navigateBack({
          //   delta:1
          // })
          resolve(res);
        } else {
          reject(res);
        }
      })

    }).catch((err) => {
      reject(err);
    })


  });
}



module.exports = {
  login,
  checkLogin,
  justGetUserInfo,
  checkPhone
};
